
import string
import re
import os
import sys
from pyPgSQL import PgSQL

def main(db='work', tblmask='', debugmode=False):
    '''Exports pg tables to text file
    
    Syntax:     pg_export <dbname> <table_name_regex>
                if dbname ommited, default 'work' will be used
                
    Example:    pg_export work public.invoices.{1,}
                
                pg_export work public.x\d{2}
                
                pg_export public.x\d{2}
                
                pg_export "^public.tablename$"
    '''
    print '''
    export table ''', tblmask
    opath = re.sub(r'\\', '/', os.getcwd())
    opath = re.sub('R:', 'C:/AFT/root/rDisk', opath)
    #print opath
    sqltemplate = "COPY (select * from @table@) TO '%s/@table@.csv' with DELIMITER '\t' CSV HEADER;" % (opath)
    cx = PgSQL.connect(database=db, user='postgres', host='127.0.0.1', client_encoding="UTF-8")
    cu = cx.cursor()
    tblmask = string.lower(tblmask)

    cu.execute("set client_encoding to 'UTF-8'")
    #cu.execute("set client_encoding to win1250")
    cu.execute("select * from pg_tables")
    #print cu.fetchone()
    for row in cu.fetchall():
        if debugmode: print row[0], row[1],
        tblname = "%s.%s" % (row[0], row[1])

        if re.search(tblmask, tblname):
            if debugmode: print 'matched'
            sqlstr = re.sub('@table@', tblname, sqltemplate)
            #print sqlstr
            cu.execute(sqlstr)
        else:
            if debugmode: print "."
            pass

if __name__ == "__main__":
    """ """
    if len(sys.argv) == 2: 
        main(db='work', tblmask=sys.argv[1])
    elif len(sys.argv) == 3: 
        main(db=sys.argv[1], tblmask=sys.argv[2])
    else: 
        print main.__doc__
        os.system('pause')


